package cn.edu.sjtu.se.dslab.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.sjtu.se.dslab.action.bean.PageBean;
import cn.edu.sjtu.se.dslab.auth.User;
import cn.edu.sjtu.se.dslab.dao.IProjectDao;
import cn.edu.sjtu.se.dslab.dao.IUserDao;
import cn.edu.sjtu.se.dslab.dao.IUserProjectDao;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.project.PGroup;
import cn.edu.sjtu.se.dslab.project.Project;
import cn.edu.sjtu.se.dslab.project.UserProject;
import cn.edu.sjtu.se.dslab.service.IUserProjectService;

@Service("userProjectService")
@Transactional
public class UserProjectServiceImpl implements IUserProjectService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Resource(name = "userProjectDao")
	private IUserProjectDao userProjectDao;
	
	@Resource(name = "projectDao")
	private IProjectDao projectDao;
	
	@Resource(name = "userDao")
	private IUserDao userDao;

	@Override
	public boolean addUserProject(UserProject userProject) {
		userProjectDao.save(userProject);
		return true;
	}
	
	@Override
	public boolean addUserProjects(long projectId, Long[] userId, Boolean[] admin){
		Project project = projectDao.queryById(projectId);
		if (project == null) throw new NullPointerException("Project Id not exist!: " + projectId);
		List<UserProject> userProjects = userProjectDao.getListByProject(project);
		Map<Long, UserProject> userprojectMapping = new HashMap<Long, UserProject>();
		for (UserProject userProject : userProjects){
			userprojectMapping.put(userProject.getUser().getId(), userProject);
			logger.info(userProject.getProject().getId()  + "---" + userProject.getUser().getId());
		}
		for (int i = 0; i< userId.length; ++i){
			//更新原有的
			if (userprojectMapping.containsKey(userId[i])){
				UserProject userProject = userprojectMapping.get(userId[i]);
				userProject.setAdmin(admin[i]);
				userProjectDao.update(userProject);
				userprojectMapping.remove(userId[i]);
				logger.info("Update User id:" + userId[i]);
			}else{
				//
				UserProject userProject = new UserProject();
				userProject.setAdmin(admin[i]);
				userProject.setProject(projectDao.queryById(projectId));
				userProject.setUser(userDao.queryById(userId[i]));
				userProjectDao.save(userProject);
				logger.info("Add User id:" + userId[i]);
			}
		}
		//删除剩下的
		for(Entry<Long,UserProject> entry: userprojectMapping.entrySet()){
			logger.info("Delete user id:" + entry.getKey());
			userProjectDao.delete(userprojectMapping.get(entry.getValue()));
			
		}
		return true;
	}

	@Override
	public boolean deleteUserProjectById(long id) {
		return userProjectDao.deleteById(id);
	}

	@Override
	public boolean deleteUserProject(UserProject userProject) {
		return userProjectDao.delete(userProject);
	}

	@Override
	public List<UserProject> getListByProject(Project project) {
		return userProjectDao.getListByProject(project);
	}

	@Override
	public List<UserProject> getListByUser(User user) {
		return userProjectDao.getListByUser(user);
	}
	
	@Override
	public List<Project> getProjectListByUser(User user) {
		List<UserProject> userProjects =  userProjectDao.getListByUser(user);
		System.out.println(userProjects.size());
		List<Project> projects = new ArrayList<Project>();
		for (UserProject up : userProjects){
			if (up.getProject().isDeleted()) continue;
			projects.add(up.getProject());
		}
		return projects;
	}

	@Override
	public PageBean<UserProject> getPageBeanByProject(int pageNo,
			Project project) throws DBException {
		return userProjectDao.getPageBeanByProject(pageNo, project);
	}

	@Override
	public boolean updateUserProject(UserProject userProject) {
		return userProjectDao.update(userProject);
	}

	@Override
	public Set<Project> getListByUserAndGroup(User user, PGroup group) {
		// TODO Auto-generated method stub
		Set<Project> resultProjects = new HashSet<Project>();
		List<UserProject> userProjects = getListByUser(user);
		if (userProjects!= null && userProjects.size()>0) {
			for (int i = 0; i < userProjects.size(); i++) {
				if (userProjects.get(i).getProject().getPgroup().getId() == group.getId()) {
					//去掉已经删除的
					Project project = userProjects.get(i).getProject();
					if (project.isDeleted()) continue;
					resultProjects.add(project);
				}
			}
		}
		return resultProjects;
	}

	@Override
	public boolean deleteUserProjectByIds(Long[] userProjectIds) {
		boolean result = true;
		for (Long id: userProjectIds){
			if (!userProjectDao.deleteById(id)) result = false;
		}
		return result;
	}

}
